package com.atguigu.gulimall.auth.controller;

import com.atguigu.common.constant.AuthServerConstant;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.auth.vo.UserRegisterVo;
import lombok.AllArgsConstructor;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Controller
public class UserController {
    @Autowired
    StringRedisTemplate stringRedisTemplate;
    @GetMapping("/sms/sendcode")
    @ResponseBody
    public R sendCode(@RequestParam("phone")String phone){
        //如果你携带phone反复调用该接口的处理
        String redisCode = stringRedisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE_PREFIX + phone);
        if (StringUtils.isNotEmpty(redisCode)){
            //走到这里证明能拿到验证码，而且还没有过期
            String s = redisCode.split("_")[1];
            if (Long.parseLong(s)-System.currentTimeMillis()<60000){
                //走这里证明你刚调了验证码的接口，还没有过1分钟
                return R.error("验证码发送过于频繁!");
            }
        }
        String s = UUID.randomUUID().toString().substring(0, 5) + "_" + System.currentTimeMillis();
        System.out.println("验证码是:"+s.substring(0,5));
        stringRedisTemplate.opsForValue().set(AuthServerConstant.SMS_CODE_CACHE_PREFIX+phone,s,5, TimeUnit.MINUTES);
        return R.ok("发送验证码成功!");
    }

    @PostMapping("/regist")
    public String regist(@Valid UserRegisterVo vo, BindingResult result, RedirectAttributes attributes
    ,HttpSession session ){
        if (result.hasErrors()){
            Map<String, String> collect = result.getFieldErrors().stream()
                    .collect(Collectors.toMap(FieldError::getField, FieldError::getDefaultMessage));
            attributes.addFlashAttribute("errors",collect);
            return "redirect:http://auth.gulimall.com/reg.html";
        }
        String code = vo.getCode();
        String s = stringRedisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE_PREFIX + vo.getPhone());
        if (StringUtils.isNotEmpty(s)){
            //就证明你这个验证码合法存在且没有过期
            if (code.equals(s.split("_")[0])){
                //走这里表示验证码输入正确
                //令牌机制，验证码校验成功后需要删除验证码，
                stringRedisTemplate.delete(AuthServerConstant.SMS_CODE_CACHE_PREFIX + vo.getPhone());

            }else {
                //走这里表示验证码存在，但是不正确
                HashMap<String, String> collect = new HashMap<>();
                collect.put("code","验证码不正确");
                attributes.addFlashAttribute("errors",collect);
                return "redirect:http://auth.gulimall.com/reg.html";
            }
        }else {
              //表示你手机发送的验证码已经过期了，或者说没点过发送验证码按钮
            HashMap<String, String> collect = new HashMap<>();
            collect.put("code","验证码不存在");
            attributes.addFlashAttribute("errors",collect);
            return "redirect:http://auth.gulimall.com/reg.html";
        }
        return "redirect:http://auth.gulimall.com/login.html";
    }
}
